﻿using Dapper;

namespace BasicModuleOrm.ProductRespository.Respository
{
    public class DapperRespository<T> : IRespository<T>, ISinglaton where T : class
    {
        private DapperContext _dapperContext;

        public DapperRespository(DapperContext dapperContext)
        {
            _dapperContext = dapperContext;
        }

        public T Add(T t)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、添加商品
                var tableName = $"`{typeof(T).Name.ToLower()}`";
                var properties = typeof(T).GetProperties().Where(p => p.Name != "Id").ToList();
                var columns = string.Join(", ", properties.Select(p => p.Name));
                var values = string.Join(", ", properties.Select(p => $"@{p.Name}"));
                var query = $"INSERT INTO {tableName} ({columns}) VALUES ({values});";
                connection.ExecuteScalar<int>(query, t);

                // 3、返回商品
                return t;
            }
        }

        public void Delete(int id)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、删除商品
                connection.Execute($"delete from {typeof(T).Name} where Id = @Id", new { Id = id });
            }
        }

        public IEnumerable<T> GetAll()
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、查询商品
                var s = connection.Query<T>($"select * from {typeof(T).Name}").ToList();

                // 3、返回商品
                return s;
            }
        }

        public T Get(int id)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、查询商品
                var t = connection.QuerySingleOrDefault<T>($"select * from {typeof(T).Name} where Id=@Id", new { Id = id });

                // 3、返回商品
                return t;
            }
        }

        public void Update(int id, T t)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、更新
                var tableName = $"`{typeof(T).Name.ToLower()}`";
                var properties = typeof(T).GetProperties().Where(p => p.Name != "Id").ToList();
                var setClause = string.Join(", ", properties.Select(p => $"{p.Name} = @{p.Name}"));
                var query = $"UPDATE {tableName} SET {setClause} WHERE Id = @Id";

                // 假设 t 是你要更新的对象
                connection.Execute(query, t);
            }
        }
    }
}
